package net.yb.ums.servlet;

import net.yb.ums.entity.User;
import net.yb.ums.service.UserService;
import net.yb.ums.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * 项目开发，建议使用三层架构！！！
 * 1.数据访问层 DAO：Data Access Object，用来操作数据库
 * 2.业务逻辑层 Service，用来处理业务逻辑
 * 3.控制层 Controller/Servlet，用来处理请求和响应
 *
 * 关系：控制层——>业务逻辑层——>数据访问层
 */
@WebServlet("/register")
public class RegisterServlet extends HttpServlet {

    private UserService userService = new UserServiceImpl();

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        /**
         * 处理请求
         */
        String name = req.getParameter("name"); // 用户名
        String pwd = req.getParameter("pwd"); // 密码
        int age = Integer.parseInt(req.getParameter("age"));
        String sex = req.getParameter("sex");
        double height = Double.parseDouble(req.getParameter("height"));
        User user = new User();
        user.setName(name);
        user.setPwd(pwd);
        user.setAge(age);
        user.setSex(sex);
        user.setHeight(height);

        /**
         * 响应
         */
        resp.setContentType("text/html; charset=utf8");
        PrintWriter out = resp.getWriter();

        // 调用业务逻辑层，进行业务处理
        try {
            userService.register(user);
            out.print("<h1 style='color:green;'>注册成功！</h1>");
        } catch (Exception e) {
            e.printStackTrace(); // 打印异常信息
            out.print("<h1 style='color:green;'>注册失败：用户已存在！</h1>");
        }

        out.close();
    }
}
